import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, logout as logoutApi } from '@/api/auth'
import { getUserMenuTree } from '@/api/menu'
import { resetRouter } from '@/router'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const userMenus = ref(JSON.parse(localStorage.getItem('userMenus') || '[]'))
  const userPermissions = ref(JSON.parse(localStorage.getItem('userPermissions') || '[]'))

  const isLoggedIn = computed(() => !!token.value)
  const hasPermission = (permission) => {
    // 检查是否为超级管理员
    const isSuperAdmin = checkIsSuperAdmin()
    if (isSuperAdmin) {
      return true
    }

    return userPermissions.value.includes(permission)
  }

  /**
   * 检查是否为超级管理员
   * @returns {Boolean} 是否为超级管理员
   */
  const checkIsSuperAdmin = () => {
    const currentUserInfo = userInfo.value

    // 检查用户信息中是否包含角色信息
    if (currentUserInfo && currentUserInfo.roles) {
      // 如果是数组，检查是否包含 super_admin
      if (Array.isArray(currentUserInfo.roles)) {
        return currentUserInfo.roles.some(role => role.code === 'super_admin')
      }
      // 如果是单个角色对象
      else if (currentUserInfo.roles.code) {
        return currentUserInfo.roles.code === 'super_admin'
      }
    }

    // 检查用户信息中的 roleCode 字段
    if (currentUserInfo && currentUserInfo.roleCode) {
      return currentUserInfo.roleCode === 'super_admin'
    }

    return false
  }

  const login = async (loginForm) => {
    try {
      const response = await loginApi(loginForm)
      const { token: newToken, user } = response

      token.value = newToken
      userInfo.value = user

      localStorage.setItem('token', newToken)
      localStorage.setItem('userInfo', JSON.stringify(user))

      // 获取用户菜单和权限
      await fetchUserMenus()

      return response
    } catch (error) {
      throw error
    }
  }

  const fetchUserMenus = async () => {
    try {
      const menuTree = await getUserMenuTree(userInfo.value.id)
      userMenus.value = menuTree

      // 提取权限标识
      const permissions = []
      const extractPermissions = (menus) => {
        menus.forEach(menu => {
          if (menu.permission) {
            permissions.push(menu.permission)
          }
          if (menu.children && menu.children.length > 0) {
            extractPermissions(menu.children)
          }
        })
      }
      extractPermissions(menuTree)
      userPermissions.value = permissions

      localStorage.setItem('userMenus', JSON.stringify(menuTree))
      localStorage.setItem('userPermissions', JSON.stringify(permissions))
    } catch (error) {
      // 获取用户菜单失败处理
    }
  }

  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      // Logout error handling
    } finally {
      token.value = ''
      userInfo.value = {}
      userMenus.value = []
      userPermissions.value = []
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('userMenus')
      localStorage.removeItem('userPermissions')
      resetRouter()
      window.location.href = '/login'
    }
  }

  const updateUserInfo = (user) => {
    userInfo.value = user
    localStorage.setItem('userInfo', JSON.stringify(user))
  }

  return {
    token,
    userInfo,
    userMenus,
    userPermissions,
    isLoggedIn,
    hasPermission,
    login,
    logout,
    updateUserInfo,
    fetchUserMenus
  }
})